package de.tabiteuea.gui.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import de.tabiteuea.gui.UIView;
import de.tabiteuea.gui.models.ModelProvider;
import de.tabiteuea.gui.wizards.NewProjectWizard;

/**
 * Handler creates a new project. To do this it calls a wizard with the input
 * mask for the project name and the project input file.
 * <p>
 * When a valid input was confirmed the UI-View will be opened with a new model.
 * 
 * @author Sebastian Lippert
 * 
 */

public class NewProjectHandler extends AbstractHandler {

	/**
	 * Execute handler
	 */

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		// call common wizard with OpenProjectWizard
		NewProjectWizard wizard = new NewProjectWizard();

		IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow();
		IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
		WizardDialog dlg = new WizardDialog(activeWorkbenchWindow.getShell(),
				wizard);

		// OK was pressed which indicates, that a new model exists
		if (dlg.open() == Dialog.OK) {

			// try to find UI-View and activate or show it
			try {
				UIView view = (UIView) activePage.findView(UIView.ID);
				if (view == null)
					view = (UIView) activePage.showView(UIView.ID);
				else
					activePage.activate(view);

				// get ModelProvider an set global model at UIView
				ModelProvider provider = ModelProvider.getInstance();
				// load model
				view.loadModel(provider.getInputModel());

			} catch (PartInitException e) {
				throw new RuntimeException(e);
			}

		}
		return null;
	}

}
